# -*- coding: utf-8 -*-

from typing import Annotated
from datetime import datetime, timedelta

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session

from myDB import SessionLocal
from myModel import Model
from myOAuth import (create_access_token, authenticate_user, authenticate_token,
                     Token, fake_users_db, ACCESS_TOKEN_EXPIRE_MINUTES)

# 导入myPackage包中的所有模块
# 导入main是为了给数据库testDB中的 abc表注入一条数据
from myPackage import *  # ['main']


# 创建FastAPI应用实例
app = FastAPI()

# 配置CORS， 允许所有来源， 方法和头
origins = [
    # "http://localhost:3000",  # 允许Nuxt.js应用的源
    # 也可以添加 其ta源， 或者使用 "*" 来允许所有源（但请注意， 这可能会带来安全风险）
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 定义依赖项， 用于请求中提供数据库会话
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义路由，用于获取abc 表中的name 字段
@app.get('/h-dong/')
async def abc_hd(db: Session = Depends(get_db)):
    # 获取当前时间
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # .a null!
    print(f"\n>> >   '/h-dong/' |Request received at：")
    print(f"________________________________ \t\t{current_time}")

    data = {}  # 初始化data

    # 查询第一个name 字段值为 'Abc' 的记录
    first_match = db.query(Model).filter(Model.name == 'Abc').first()
    if first_match:
        data['hDong_data'] = first_match.name
    else:
        data['hDong_data'] = None

    return data


# OAuth2 配置
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


@app.post('/token/')
async def login_for_access_token(
    form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
) -> Token:
    user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )

    return Token(access_token=access_token, token_type="bearer")


# 定义依赖项，用于请求中提供数据库会话
def get_db_oauth(token: Annotated[str, Depends(oauth2_scheme)]):
    authenticate_token(token)
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义路由，用于获取abc 表中的name 字段
@app.get('/oauth/')
async def abc_oauth(db: Session = Depends(get_db_oauth)):
    # 获取当前时间
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")  # .a null!
    print(f"\n>> >   '/oauth/' |Request received at：")
    print(f"________________________________ \t\t{current_time}")

    data = {}  # 初始化data

    # 查询第一个name 字段值为 'Abc' 的记录
    first_match = db.query(Model).filter(Model.name == 'Abc').first()
    if first_match:
        data['hDong_data'] = first_match.name
    else:
        data['hDong_data'] = None

    return data


print('__________________________________________>   helo,  Gitee!')
# 运行FastAPI 应用
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="localhost", port=8001)
